#include "mysql.h"
#include "jwt.h"

int main(){
    MYSQL *conn = NULL;                                                                                                              
    connectDB(&conn);
    while(1){
        printf("请输入用户名:\n");
        char username[50] = {0};
        scanf("%s", username);
        char where1[SQL_MAX] = {0};
        sprintf(where1, "username = '%s'", username);
        char user_id[11] = {0};
        strcpy(user_id, searchTableData(conn, "user", "id", where1));
        if(strlen(user_id) == 0){ 
            //用户不存在，请注册 
            printf("该用户名不存在，是否进行注册？(Y/N)\n");
            char inquire[16] = {0};
            scanf("%s", inquire);
            if(strcmp(inquire, "Y") == 0){
                printf("请输入密码:\n");
                char passwd[54] = {0};
                scanf("%s", passwd);
                char salt[20] = {0}; 
                char cryptpasswd[200] = {0};
                strcpy(cryptpasswd, crypt(passwd, GenerateSalt
                                          (salt)));            
                char pwd[100] = {0}; 
                sprintf(pwd, "/%s", username);
                char fields[4096] = "username, salt, cryptpasswd,pwd, token";
                char values[4096] = {0};
                sprintf(values, "'%s', '%s', '%s', '%s', '%s'",
                        username, salt, cryptpasswd, pwd, "0");
                addTableData(conn, "user", fields, values);
                memset(&fields, 0, 4096);
                memset(&values, 0, 4096);
                sprintf(fields, "parent_id, filename, owner_id, md5, type, cnt");
                sprintf(values, "-1, '%s', %d, 'dir', 1, 1", username, atoi(user_id));
                addTableData(conn, "vrfile", fields, values);
                break;
            }
        }else{
            //用户存在，验证密码
            printf("请输入密码:\n");
            char passwd[54] = {0};
            scanf("%s", passwd);
            char salt[20] = {0};
            char cryptpasswd[200] = {0};
            strcpy(salt, searchTableData(conn, "user", "salt", where1));
            if(strcmp(crypt(passwd, salt),
                      searchTableData(conn, "user", "cryptpasswd",
                                      where1)) == 0){
                printf("登陆成功！\n");
                char token[512] = {0};
                strcpy(token, encode(token, user_id));
                char newfield[SQL_MAX] = {0};
                sprintf(newfield, "token = '%s'", token);
                altTabledata(conn, "user", newfield, where1);     
                char values[SQL_MAX] = {0};
                sprintf(values, "'%s', '%s', '%s'", user_id, token, "2022-10-20");
                addTableData(conn, "token", "user_id, token, expire",
                             values);
                break;
            }else{
                printf("密码错误，请重新登录\n");
                continue;
            }
        }
    }
    mysql_close(conn);
}

